#!/bin/sh

## Copyright (c) 2010-2011, Michael D. Adams
## <http://www.cs.indiana.edu/~adamsmd/>
## 
## Permission to use, copy, modify, and/or distribute this software for any
## purpose with or without fee is hereby granted, provided that the above
## copyright notice and this permission notice appear in all copies.
## 
## THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
## WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
## MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
## ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
## WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
## ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
## OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

# usage example:
#   backup.sh title /path/to/source -bwlimit 100
# max backup copies to keep:
MAX_SAVED_BACKUPS=50


if [ -z "$DEBUG" ]; then
	source $(dirname $0)/_common.sh
fi
# get lock
create_lock "backup.lock"
if [[ ${#} -ge 4 && "${3}" -eq "bwlimit" ]]; then
	bwlimit="${4}"
else
	bwlimit="8192"
fi

title "Backing up ${1}"
sleep 1

SRC=$2 # no slash at end
DST=${PXN_BACKUPS}/$1 # no slash at end

mkdir "$DST" 2> /dev/null

# If backup.0 already exists then bump age numbers and remove old backup.max
if [ ! -d "$DST/${1}.0" ]; then
	echo "No existing backups found."
fi

# find oldest backup to rename
count=0
while true ; do
	echo -n " $count | "
	# dir doesn't exist
	if [ -d "$DST/${1}.$count" ]; then
		echo "Found backup"
	else
		echo "No backup found.."
		echo -n "Found a gap in the backups, using slot # $count ."; sleepdot
		break
	fi
	(( count++ ))
	if [[ $count -gt $[MAX_SAVED_BACKUPS-1] ]]; then
		count=$((count-1))
		echo -n "Max backups reached, Deleting oldest # $count ."; sleepdot
		echo rm -rvf "$DST/${1}.$count"
		rm -rf "$DST/${1}.$count"
		break
	fi
done

# bump down
while [[ $count -ge 1 ]]; do
	echo mv -v "$DST/${1}.$[$count-1]" "$DST/${1}.$[$count]"
	mv -v "$DST/${1}.$[$count-1]" "$DST/${1}.$[$count]"
	count=$count-1
done
sleep 1

# --progress: so we know if the program froze
# --archive:
#     recursive, links, permissions, times, group, owner, devices, specials
# --delete: remove no longer existant files in old backup.pre.
#     We don't delete the entire old backup.pre so we can do a fast restart.
# -F: use per-directory ".rync-filter" files to filter
# --rsh: tunnel over SSH
# --link-dest: share hard links to unchanged files with previous backup

mkdir "$DST/${1}.pre" 2> /dev/null
echo rsync --progress --archive --delete-delay -Fyth --bwlimit="${bwlimit}" --link-dest="$DST/${1}.1" "$SRC" "$DST/${1}.pre"
rsync --progress --archive --delete-delay -Fyth --bwlimit="${bwlimit}" --link-dest="$DST/${1}.1" "$SRC" "$DST/${1}.pre" && /
mv "$DST/${1}.pre" "$DST/${1}.0"

# remove lock
remove_lock "backup.lock"
title "Finished backup of ${1} !"

